import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_base_widget/base/base_app.dart';
import 'package:flutter_base_widget/code2/second_page.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

//静态路由配置
void main() => runApp(BaseApp(homeWidget: Exam205HomePage()));

class Exam205HomePage extends StatefulWidget {
  @override
  State<Exam205HomePage> createState() => _Exam205HomePageState();
}


///lib/code7/code701_main_page.dart
class _Exam205HomePageState extends State<Exam205HomePage> {
  int _data = 0;

  @override
  Widget build(BuildContext context) {
    //Scaffold 用来搭建页面的主体结构
    return Scaffold(
      //页面的主内容区
      body: Center(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: () {
                _data++;

                ///第三步就是数据变化后赋值更新
                testValueNotifier.value = '$_data';
              },
              child: const Text("+"),
            ),
            const SizedBox(width: 40),
            Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                BPage(),
                const SizedBox(height: 20),
                CPage(),
                const SizedBox(height: 20),
              ],
            )
          ],
        ),
      ),
    );
  }
}

/// 第一步 定义 ValueNotifier  这里传递的数据类型为 String
ValueNotifier<String> testValueNotifier = ValueNotifier<String>('');

///代码清单 7-2-1
/// 第二步 在需要同步数据的地方使用
///lib/code7/code701_main_page.dart
class BPage extends StatelessWidget {
  const BPage({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder(
      //数据发生变化时回调
      builder: (context, value, child) {
        return Text("B未获取到数据 $value");
      },
      //监听的数据
      valueListenable: testValueNotifier,
    );
  }
}
class CPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder(
      //数据发生变化时回调
      builder: (context, value, child) {
        return Text("C中获取到数据 $value");
      },
      //监听的数据
      valueListenable: testValueNotifier,
    );
  }
}

  ///代码清单 7-1-1
  ///lib/code7/code701_main_page.dart
  @immutable
  class CountInherited extends InheritedWidget {
  //共享数据
  final int data;
  const CountInherited({Key? key, this.data = 0, required Widget child})
      : super(key: key, child: child);

  //定义一个方法，方便子树中的widget获取这个widget，进而获得共享数据。
  static CountInherited? of(BuildContext context) {
  return context.dependOnInheritedWidgetOfExactType<CountInherited>(
  aspect: CountInherited);
  }

  @override
  bool updateShouldNotify(CountInherited oldWidget) {
  return true;
  }
  }
